﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;
using LinqToLfsWorld.Extensions;

namespace LinqToLfsWorld.Queries
{
	/// <summary>
	/// Queries LfsWorld for information on world records.
	/// </summary>
	public class WorldRecordQuery : LfsWorldQuery<WorldRecord>
	{

		/// <summary>
		/// Initializes a new instance of the <see cref="WorldRecordQuery"/> class.
		/// </summary>
		/// <param name="context">The context.</param>
		public WorldRecordQuery(LfsWorldContext context)
			: base(context)
		{
		}

		/// <summary>
		/// Gets the URL used to query LfsWorld.
		/// </summary>
		/// <returns></returns>
		protected override string GetUrl()
		{
			string url = LfsHelper.GetPubstatUrlBase(PubstatResponseType.Xml, this, "wr");

			if (ExpressionValues.ContainsKey("Car"))
				url += "&car=" + (string)ExpressionValues["Car"].Value;

			if (ExpressionValues.ContainsKey("TrackIdent"))
				url += "&track=" + (string)ExpressionValues["TrackIdent"].Value;

			return url;
		}

		/// <summary>
		/// Gets the entities given LfsWorld response XML
		/// </summary>
		/// <param name="responseData">The response data.</param>
		/// <returns>A collection of Host entities</returns>
		protected override IEnumerable<WorldRecord> ProcessResponse(string responseData)
		{
			XDocument doc = XDocument.Parse(responseData);

			if (doc.Root.Name == "wr_data")
			{
				var entries = doc.Descendants("entry");

				foreach (var node in entries)
				{
					WorldRecord wr = new WorldRecord();

					wr.RacerName = node.Element("racername").Value.StripLfsColours();
					wr.TrackIdent = node.Element("track").Value;
					wr.TrackName = Utility.CircuitNameFactory.GetNameFromIdent(wr.TrackIdent);
					wr.Car = node.Element("car").Value;
					wr.Split1 = TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("split1").Value));
					wr.Split2 = TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("split2").Value));
					wr.Split3 = TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("split3").Value));
					wr.LapTime = TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("laptime").Value));
					wr.Id = Convert.ToInt32(node.Element("id_wr").Value);
					wr.Flags = (HotlapFlags)Convert.ToInt32(node.Element("flags_hlaps").Value);

					yield return wr;
				}

			}

		}
	}
}
